package com.thread.laoma;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * @author zhuangqi
 * @@date 2017/3/27.
 */
public class PCThreadTest {


    static class MyBlockingQueue<E>{

        private Queue<E> queue = null;
        private int limit;

        public MyBlockingQueue(int limit){
            this.limit = limit;
            queue = new ArrayDeque<E>(limit);
        }

        public synchronized void put(E e) throws InterruptedException{
            while (queue.size() == limit){
                wait();
            }
            queue.add(e);
            notifyAll();
        }

        public synchronized E take() throws InterruptedException{
            while (queue.isEmpty()){
                wait();
            }
            E e = queue.poll();
            notifyAll();
            return e;
        }
    }

    static class Producer extends Thread {

        MyBlockingQueue<String> queue;

        public Producer(MyBlockingQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            int num = 0;
            try {
                while (true){
                    String task = String.valueOf(num);
                    queue.put(task);
                    System.out.println("生产 task" + task);
                    num++;
                    Thread.sleep((int)(Math.random()*100));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Custom extends Thread {

        MyBlockingQueue<String> queue;

        public Custom(MyBlockingQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true){
                try {
                    String task = queue.take();
                    System.out.println("消费 task" + task);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        MyBlockingQueue<String> queue = new MyBlockingQueue<String>(10);
        new Producer(queue).start();
        new Custom(queue).start();
    }
}


